// 存储已发现的资源
let discoveredResources = {
    images: new Set(),
    videos: new Set(),
    audios: new Set()
};

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    if (request.action === 'getResources') {
        // 首次获取资源
        updateAllResources();
        
        // 返回当前资源
        const resources = {
            images: Array.from(discoveredResources.images),
            videos: Array.from(discoveredResources.videos),
            audios: Array.from(discoveredResources.audios)
        };
        sendResponse(resources);
    }
    return true; // 保持消息通道开启
});

// 创建 MutationObserver 实例
const observer = new MutationObserver((mutations) => {
    let hasNewContent = false;
    
    mutations.forEach((mutation) => {
        if (mutation.type === 'childList' || mutation.type === 'attributes') {
            hasNewContent = true;
        }
    });
    
    if (hasNewContent) {
        // 延迟执行以等待动态内容完全加载
        setTimeout(updateAllResources, 500);
    }
});

// 开始观察页面变化
observer.observe(document.body, {
    childList: true,
    subtree: true,
    attributes: true,
    attributeFilter: ['src', 'data-src', 'data-original', 'style']
});

// 更新所有资源
function updateAllResources() {
    const newImages = getImages();
    const newVideos = getVideos();
    const newAudios = getAudios();
    
    let hasChanges = false;
    
    // 更新图片资源
    newImages.forEach(img => {
        const key = JSON.stringify({src: img.src, type: img.type});
        if (!Array.from(discoveredResources.images).some(x => JSON.stringify({src: x.src, type: x.type}) === key)) {
            discoveredResources.images.add(img);
            hasChanges = true;
        }
    });
    
    // 更新视频资源
    newVideos.forEach(video => {
        const key = JSON.stringify({src: video.src, type: video.type});
        if (!Array.from(discoveredResources.videos).some(x => JSON.stringify({src: x.src, type: x.type}) === key)) {
            discoveredResources.videos.add(video);
            hasChanges = true;
        }
    });
    
    // 更新音频资源
    newAudios.forEach(audio => {
        const key = JSON.stringify({src: audio.src, type: audio.type});
        if (!Array.from(discoveredResources.audios).some(x => JSON.stringify({src: x.src, type: x.type}) === key)) {
            discoveredResources.audios.add(audio);
            hasChanges = true;
        }
    });
    
    // 如果有新资源，通知popup更新
    if (hasChanges) {
        chrome.runtime.sendMessage({
            action: 'resourcesUpdated',
            resources: {
                images: Array.from(discoveredResources.images),
                videos: Array.from(discoveredResources.videos),
                audios: Array.from(discoveredResources.audios)
            }
        });
    }
}

// 获取页面中的所有图片
function getImages() {
    const images = Array.from(document.getElementsByTagName('img'));
    const backgroundImages = getBackgroundImages();
    
    const imageResources = images.map(img => ({
        src: img.src,
        dataSrc: img.getAttribute('data-src'),
        srcset: img.srcset,
        alt: img.alt || '未命名图片',
        type: 'image',
        filename: getFilenameFromUrl(img.src, 'image'),
        width: img.naturalWidth || img.width,
        height: img.naturalHeight || img.height,
        dataOriginal: img.getAttribute('data-original'),
        lazyLoadSrc: img.getAttribute('data-lazy') || img.getAttribute('data-lazy-src')
    }));

    return [...imageResources, ...backgroundImages]
        .filter(img => (img.src || img.dataSrc || img.dataOriginal || img.lazyLoadSrc) && 
            (img.src?.startsWith('http') || img.dataSrc?.startsWith('http') || 
             img.dataOriginal?.startsWith('http') || img.lazyLoadSrc?.startsWith('http')))
        .filter((img, index, self) => 
            index === self.findIndex((t) => t.src === img.src)
        )
        .map(img => ({
            ...img,
            src: img.src || img.dataSrc || img.dataOriginal || img.lazyLoadSrc
        }));
}

// 获取背景图片
function getBackgroundImages() {
    const elements = document.getElementsByTagName('*');
    const backgroundImages = [];

    for (const element of elements) {
        const style = window.getComputedStyle(element);
        const backgroundImage = style.backgroundImage;
        
        if (backgroundImage && backgroundImage !== 'none') {
            const matches = backgroundImage.match(/url\(['"]?(.*?)['"]?\)/);
            if (matches && matches[1]) {
                const url = matches[1];
                backgroundImages.push({
                    src: url,
                    alt: '背景图片',
                    type: 'image',
                    filename: getFilenameFromUrl(url, 'image'),
                    isBackground: true
                });
            }
        }
    }

    return backgroundImages;
}

// 获取页面中的所有视频
function getVideos() {
    const videos = Array.from(document.getElementsByTagName('video'));
    const sources = Array.from(document.getElementsByTagName('source'));
    const iframes = Array.from(document.getElementsByTagName('iframe'));
    const videoElements = Array.from(document.querySelectorAll('[data-video-url], [data-video-src], [data-video]'));
    
    const videoSources = videos.map(video => {
        const sources = Array.from(video.getElementsByTagName('source'));
        const videoUrls = sources.length > 0 
            ? sources.map(source => source.src).filter(Boolean)
            : [video.src || video.currentSrc].filter(Boolean);
            
        return videoUrls.map(url => ({
            src: url,
            poster: video.poster,
            type: 'video',
            filename: getFilenameFromUrl(url, 'video'),
            width: video.videoWidth || video.width,
            height: video.videoHeight || video.height
        }));
    }).flat();
    
    const sourceVideos = sources
        .filter(source => source.type && source.type.startsWith('video/'))
        .map(source => ({
            src: source.src,
            type: 'video',
            filename: getFilenameFromUrl(source.src, 'video'),
            mediaType: source.type
        }));

    const iframeVideos = iframes
        .filter(iframe => {
            const src = iframe.src.toLowerCase();
            return src.includes('youtube.com') || 
                   src.includes('vimeo.com') ||
                   src.includes('dailymotion.com') ||
                   src.includes('youku.com') ||
                   src.includes('iqiyi.com') ||
                   src.includes('bilibili.com');
        })
        .map(iframe => ({
            src: iframe.src,
            type: 'video',
            filename: `video_${Date.now()}.mp4`,
            width: iframe.width,
            height: iframe.height,
            isEmbed: true
        }));

    const dataVideos = videoElements
        .map(element => {
            const videoUrl = element.getAttribute('data-video-url') || 
                           element.getAttribute('data-video-src') ||
                           element.getAttribute('data-video');
            if (videoUrl) {
                return {
                    src: videoUrl,
                    type: 'video',
                    filename: getFilenameFromUrl(videoUrl, 'video')
                };
            }
            return null;
        })
        .filter(Boolean);
    
    return [...videoSources, ...sourceVideos, ...iframeVideos, ...dataVideos]
        .filter(video => video.src && video.src.startsWith('http'))
        .filter((video, index, self) => 
            index === self.findIndex((t) => t.src === video.src)
        );
}

// 获取页面中的所有音频
function getAudios() {
    const audios = Array.from(document.getElementsByTagName('audio'));
    const sources = Array.from(document.getElementsByTagName('source'));
    
    const audioSources = audios.map(audio => {
        const sources = Array.from(audio.getElementsByTagName('source'));
        const audioUrls = sources.length > 0 
            ? sources.map(source => source.src).filter(Boolean)
            : [audio.src || audio.currentSrc].filter(Boolean);
            
        return audioUrls.map(url => ({
            src: url,
            type: 'audio',
            filename: getFilenameFromUrl(url, 'audio'),
            duration: audio.duration
        }));
    }).flat();
    
    const sourceAudios = sources
        .filter(source => source.type && source.type.startsWith('audio/'))
        .map(source => ({
            src: source.src,
            type: 'audio',
            filename: getFilenameFromUrl(source.src, 'audio'),
            mediaType: source.type
        }));
    
    return [...audioSources, ...sourceAudios]
        .filter(audio => audio.src && audio.src.startsWith('http'))
        .filter((audio, index, self) => 
            index === self.findIndex((t) => t.src === audio.src)
        );
}

// 从URL中获取文件名
function getFilenameFromUrl(url, defaultType) {
    if (!url) return `${defaultType}_${Date.now()}.${getDefaultExtension(defaultType)}`;
    
    try {
        const urlObj = new URL(url);
        const pathname = urlObj.pathname;
        const filename = pathname.split('/').pop();
        
        if (filename && filename.includes('.')) {
            return decodeURIComponent(filename);
        } else {
            const timestamp = new Date().getTime();
            return `${defaultType}_${timestamp}.${getDefaultExtension(defaultType)}`;
        }
    } catch (e) {
        const timestamp = new Date().getTime();
        return `${defaultType}_${timestamp}.${getDefaultExtension(defaultType)}`;
    }
}

// 获取默认文件扩展名
function getDefaultExtension(type) {
    const extensions = {
        'image': 'jpg',
        'video': 'mp4',
        'audio': 'mp3'
    };
    return extensions[type] || 'unknown';
} 